import { defineStore } from 'pinia'
import { __SEARCH_HISTORY_KEY__ } from '@/utils/constant'
type initState = {
  historyList: string[]
}
function getCacheData(key: string) {
  try {
    return JSON.parse(localStorage.getItem(key) || '[]')
  } catch {
    return []
  }
}
export const useSearchHistoryStore = defineStore('searchHistoryStore', {
  // 推荐使用 完整类型推断的箭头函数
  state: (): initState => {
    return {
      historyList: getCacheData(__SEARCH_HISTORY_KEY__)
    }
  },
  actions: {
    // 添加一条记录
    addHistoryRecord(text: string): void {
      const index = this.historyList.findIndex((value) => value === text)
      if (index > -1) {
        const [delEle] = this.historyList.splice(index, 1)
        this.historyList.unshift(delEle)
      } else {
        this.historyList.unshift(text)
      }
      localStorage.setItem(__SEARCH_HISTORY_KEY__, JSON.stringify(this.historyList))
    },
    // 删除一条记录
    delHistoryRecord(text: string) {
      const index = this.historyList.findIndex((value) => value === text)
      if (index > -1) {
        this.historyList.splice(index, 1)
        localStorage.setItem(__SEARCH_HISTORY_KEY__, JSON.stringify(this.historyList))
      }
    },
    // 清除所有的记录
    clearHistoryRecord() {
      this.historyList = []
      localStorage.removeItem(__SEARCH_HISTORY_KEY__)
    }
  }
})
